package com.choker.mall.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * Created by Lychee on 2018/3/9 08:34.
 * <p>
 * Author:Hejingzhou
 * <p>
 * Email:tcowork@163.com
 */
@Controller
public class FileDownloadController {

    /**
     * 这里的下载不能是利用上传文件处的Demo  因为在重启tomcat 的时候会把/usr/local/Cellar/tomcat/8.5.15/libexec/webapps/ROOT/images/psb.jpeg ROOT下创建的
     * 文件夹删除  会报FileNotFoundException
     */
    @RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
    public ResponseEntity<byte[]> downloadImage(HttpServletRequest request, @RequestParam(value = "psb.jpeg", defaultValue = "psb.jpeg") String fileName) throws IOException {
        String rootPath = request.getServletContext().getRealPath("/images/");
        File file = new File(rootPath + File.separator + fileName);
        HttpHeaders httpHeaders = new HttpHeaders();

        //下载显示的文件名称 解决中文乱码问题
        String downloadFileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");

        httpHeaders.setContentDispositionFormData("attachment", downloadFileName);
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), httpHeaders, HttpStatus.CREATED);
        return responseEntity;
    }
}
